<?php

namespace App\Console\Commands;

use App\Http\Models\UserAmountLog;
use App\Http\Models\ZtkOrder;
use App\Http\Models\ZtkUser;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class TheUrgentOrderStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'TheUrgentOrderStatus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '即时失效加急任务的接单 30分钟未完成即失效';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $date = date('Y-m-d H:i:s',strtotime('-30 minute')); //30分钟前的时间
        //echo $date;exit;

        $data = ZtkOrder::where('status',1)      //查出30分钟之前接单还没完成的人
            ->whereHas('task',function ($query){
                $query->where('send_date',4);
            })
            ->where('updated_at','<',$date)      //可能是指派单用修改时间算
            ->get();

        if($data->isNotEmpty())
        {
            foreach($data as $key=>$value)
            {
                DB::beginTransaction();
                try {

                    //失效接单
                    ZtkOrder::where('id',$value->id)->where('status',1)->update(['status'=>3]);

                    //罚款金额
                    $returnMoney = 58;

                    //罚款
                    $user1 = ZtkUser::find($value->user_id);
                    $amount = $user1->amount - $returnMoney; //账户余额
                    $trade_no = get_order_no($user1->id);
                    $user1->amount = $amount;
                    $user1->save();

                    //罚款记录
                    UserAmountLog::create([
                        'user_id'  => $user1->id,
                        'trade_no' => $trade_no,
                        'amount'   => $returnMoney,
                        'after_amount' => $user1->amount,
                        'type'     => 2,
                        'class'    => 9,
                        'task_id'  => $value->task_id,
                    ]);

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack(); continue;
                }
            }
        }

    }

}
